package com.mai.util;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

public class UploadUtil {
	public static String UploadFile(MultipartFile file, HttpServletRequest request) {
		//获取上传文件的名称
		String name = file.getOriginalFilename();
		//获取上传文件的路径
		String path = request.getServletContext().getRealPath("/uploads");
		//重新生成文件名，避免文件名重复而报错
		String str = UUID.randomUUID().toString();
		String fileName = str + name;
		
		File filePath = new File(path, fileName);
		try {
			//判断文件的目录是否存在，不存在则创建
			if(!filePath.getParentFile().exists()){
				filePath.getParentFile().mkdir();
			}
			//判断文件是否存在，存在则删除
			if(filePath.exists()){
				filePath.delete();
			}
			file.transferTo(filePath);
		}catch (Exception e) {
			
			e.printStackTrace();
		}
		return fileName;
		
	}
}
